// pages/history/history.js
const STORAGE_KEYS = require('../../configs/STORAGE_KEYS');
const { calcFinalPoints } = require('../../business/calcPoints')
const { formatTime } = require('../../utils/util')
const playersStore = require('../../stores/players')
const { getFinalScores } = require('../../business/score')

Page({
  data: {
    historyList: [],
    gameRemarks: {},
    searchInput: '',
    search: '',
    // 是否展示搜索内容
    showSearchResult: false,
    // 搜索到的对局数据
    searchedGameNums: [],
    // 是否有搜索到数据
    hasList: false,
  },
  onLoad() {
    const historyGameNums = wx.getStorageSync(STORAGE_KEYS.HISTORY_GAME_NUMS) || [];
    this.setGameRemarks()
    this.setHistoryRecords(historyGameNums)
  },
  setHistoryRecords(historyGameNums) {
    const historyList = [];
    const { gameRemarks } = this.data;
    historyGameNums.forEach(key => {
      const records = wx.getStorageSync(key);
      let [, startTime, playerStr] = key.split('_');
      startTime = Number(startTime);
      const playerNums = playerStr.split('-').map(Number);
      if (records) {
        historyList.push({ remark: gameRemarks[key], records, startTime, startTimeText: formatTime(new Date(startTime)), playerNums, players: playersStore.getPlayersByNums(playerNums), gameNum: key })
      }
    })
    this.setFinalPoints(historyList);
    this.setData({ historyList, hasList: historyList.length > 0 });
  },
  setFinalPoints(historyList) {
    historyList.forEach(historyItem => {
      const { records, players } = historyItem;
      const { finalPoints, leftStickNum } = calcFinalPoints(records)
      historyItem.finals = finalPoints.map((finalPoint, index) => {
        return {
          point: finalPoint,
          nickname: players[index].nickname,
          windText: ['东', '南', '西', '北'][index],
        }
      })
      const sortedFinals = [...historyItem.finals].sort((a, b) => b.point - a.point)
      const sortedFianalPoints = sortedFinals.map(sortedFinal => sortedFinal.point);
      const scores = getFinalScores(sortedFianalPoints, leftStickNum, [50, 10, -10, -30]);
      scores.map((score, index) => {
        sortedFinals[index].score = score;
        sortedFinals[index].order = index + 1;
      })
    })
  },
  setGameRemarks() {
    const gameRemarks = wx.getStorageSync(STORAGE_KEYS.GAME_REMARKS);
    this.setData({ gameRemarks })
  },
  handleSearch() {
    const { searchInput, gameRemarks } = this.data;
    const search = searchInput.trim()
    if (!search) {
      this.handleViewAll()
      return;
    }
    const searched = Object.entries(gameRemarks).filter(([gameNum, remark]) => {
      return remark.includes(search)
    })
    const searchedGameNums = searched.map(entry => entry[0])
    this.setHistoryRecords(searchedGameNums)
    this.setData({ search, showSearchResult: true })
  },
  handleViewAll() {
    const historyGameNums = wx.getStorageSync(STORAGE_KEYS.HISTORY_GAME_NUMS) || [];
    this.setHistoryRecords(historyGameNums)
    this.setData({ showSearchResult: false, search: '', searchInput: '' })
  },
  handleDel(event) {
    const gameNum = event.detail;
    const { historyList } = this.data;
    this.setData({ historyList: historyList.filter(item => item.gameNum !== gameNum) })
  }
})